package com.zzh.wechatpay.controller;

import com.zzh.wechatpay.config.WeChatConfig;
import com.zzh.wechatpay.domain.JsonData;
import com.zzh.wechatpay.domain.User;
import com.zzh.wechatpay.service.UserService;
import com.zzh.wechatpay.service.VideoOrderService;
import com.zzh.wechatpay.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * 微信登录控制器
 * @author zzh
 */
@Controller
@RequestMapping("/api/v1/wechat")
public class WechatController {

    @Autowired
    private WeChatConfig weChatConfig;
    @Autowired
    private UserService userService;
    @Autowired
    private VideoOrderService videoOrderService;


    /**
     * 拼装微信扫一扫登录url
     * @param accessPage 登录成功后的地址
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("login_url")
    @ResponseBody
    public JsonData loginUrl(@RequestParam(value = "access_page")String accessPage) throws UnsupportedEncodingException {
        //获取开放平台重定向地址
        String redirectUrl = weChatConfig.getOpenRedirectUrl();
        //进行编码
        String callbackUrl = URLEncoder.encode(redirectUrl,"GBK");
        //拼接返回给前台
        String qrcodeUrl = String.format(WeChatConfig.getOpenQrcodeUrl(),weChatConfig.getOpenAppid(),callbackUrl,accessPage);
        return JsonData.buildSuccess(qrcodeUrl);
    }

    /**
     * 用户扫码后回调地址
     * @param code 授权登录后带code回调
     * @param state 之前查看的页面
     * @param response 用户响应给前台
     * @return
     */
    @GetMapping("callback")
    public void callback(@RequestParam(value = "code") String code, String state, HttpServletResponse response) throws IOException {
        User user = userService.saveWeChatUser(code);
        //用户存在,生成token,重定向到之前登录页面
        if (user != null) {
            String token = JwtUtils.geneJsonWebToken(user);
            response.sendRedirect(state+"?token="+token+"&img="+user.getHeadImg()+"&name"+URLEncoder.encode(user.getName(), "UTF-8"));
        }
        //用户认证,重定向到之前页面,无token
        response.sendRedirect(state);
    }

}
